package com.example.pixelyear.utils

import android.content.ClipData
import android.content.ClipDescription
import android.content.Context
import android.net.Uri

/**
 * Package    : com.zjedu.xueyuan.utils
 * When I wrote this, only The jade emperor and I understood what I was doing, Now God only knows
 * ClassName  : CopyUtils
 * Description: ${TODO}
 * Author     : 坐怀灬不乱
 * Date       : 2018/7/23 10:42
 */
object CopyUtils {
    /**
     * 复制文字到粘贴板
     */
    fun copyString(context: Context, label: String? = "描述", msg: String) {
        val nowManager: android.content.ClipboardManager =
            context.getSystemService(Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
        nowManager.setPrimaryClip(ClipData.newPlainText(label, msg))
    }

    /**
     *复制Uri到粘贴板
     */
    fun copyUri(context: Context, uri: Uri) {
        val nowManager: android.content.ClipboardManager =
            context.getSystemService(Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
        nowManager.setPrimaryClip(ClipData.newRawUri("描述", uri))
    }

    /**
     * 粘贴字符串
     */
    fun pasteString(context: Context): String {
        val nowManager: android.content.ClipboardManager =
            context.getSystemService(Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
        return if (nowManager.hasPrimaryClip() && nowManager.primaryClip != null && nowManager.primaryClip?.itemCount ?: 0 > 0 &&
            nowManager.primaryClipDescription?.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN) == true
        ) {
            val itemAt = nowManager.primaryClip?.getItemAt(0)
            if (itemAt != null && itemAt.text != null) {
                itemAt.text.toString()
            } else ""
        } else ""
    }

}